package cn.xiaopengstack.domain.trade.rule.trade;

import cn.xiaopengstack.domain.activity.model.entity.GroupBuyActivityEntity;
import cn.xiaopengstack.domain.activity.model.valobj.GroupBuyActivityStatusEnum;
import cn.xiaopengstack.domain.activity.repository.IActivityRepository;
import cn.xiaopengstack.domain.trade.rule.factory.TradeRuleFilterFactory;
import cn.xiaopengstack.domain.trade.model.entity.TradeRuleCommandEntity;
import cn.xiaopengstack.domain.trade.model.entity.TradeRuleResponseEntity;
import cn.xiaopengstack.domain.trade.repository.ITradeRepository;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Objects;

/**
 * @author jiangyangang
 */
@Component
@Slf4j
public class ActivityAbilityFilter extends AbstractTradeLogicLink<TradeRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeRuleResponseEntity> {


    public ActivityAbilityFilter(ITradeRepository groupBuyOrderRepository, IActivityRepository activityRepository) {
        super(groupBuyOrderRepository, activityRepository);
    }

    @Override
    public TradeRuleResponseEntity apply(TradeRuleCommandEntity request, TradeRuleFilterFactory.DynamicContext dynamic) throws Exception {
        log.info("交易规则过滤-活动的可用性校验。userId={} activityId={}", request.getUserId(), request.getActivityId());

        GroupBuyActivityEntity activityEntity = activityRepository.queryGroupBuyActivityEntityByActivityId(request.getActivityId());

        long nowMills = LocalDateTime.now().atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli();

        if (Objects.isNull(activityEntity)) {
            throw new AppException(ResponseCode.UNKNOW_ACTIVITY.getCode(), ResponseCode.UNKNOW_ACTIVITY.getInfo());
        }
        // 判断活动状态
        if (GroupBuyActivityStatusEnum.EFFECT != activityEntity.getStatus()) {
            throw new AppException(ResponseCode.INVALID_ACTIVITY.getCode(), ResponseCode.INVALID_ACTIVITY.getInfo());
        }

        // 判断活动的有效时间
        if (nowMills > activityEntity.getEndTime()) {
            throw new AppException(ResponseCode.ACTIVITY_EXPIRED.getCode(), ResponseCode.ACTIVITY_EXPIRED.getInfo());
        }

        if (activityEntity.getStartTime() > nowMills) {
            throw new AppException(ResponseCode.ACTIVITY_NO_START.getCode(), ResponseCode.ACTIVITY_NO_START.getInfo());
        }

        dynamic.setGroupBuyActivityEntity(activityEntity);

        return next(request, dynamic);
    }
}
